package com.hippo.core.vm

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.hippo.core.model.Faq
import com.hippo.core.model.Product
import com.hippo.core.source.FaqPagingSource
import com.hippo.core.source.ProductPagingSource
import com.hippo.core.respository.ApiRepository
import com.hippo.core.state.SptState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

class SptVm :ViewModel(){

    var uiState by mutableStateOf(SptState())

    val faqPager: Flow<PagingData<Faq>> =  Pager(
        config = PagingConfig(pageSize = 20),
        pagingSourceFactory = { FaqPagingSource() }
    ).flow.cachedIn(viewModelScope)


    val productPager: Flow<PagingData<Product>> =  Pager(
        config = PagingConfig(pageSize = 20),
        pagingSourceFactory = { ProductPagingSource() }
    ).flow.cachedIn(viewModelScope)



    fun getProductDetail(productId:Int){
        viewModelScope.launch {
            ApiRepository.getProductDetail(productId)
                .onSuccess {
                    uiState = uiState.copy(
                        productDetail = it
                    )
                }

        }
    }


    fun getSptDetail(faqId:Int){
        viewModelScope.launch {
            ApiRepository.getProductFaqDetail(faqId)
                .onSuccess {
                    uiState = uiState.copy(
                        faqDetail = it
                    )
                }
        }
    }


}